#!/usr/bin/python
#-*- coding: utf-8 -*-

# subversion info:
# $HeadURL: $
# $Author: $
# $Id: $
# $Revision: $

"""
  sub-daemon: Subtitle download daemon.
  Authors = Rafael Treviño <skasi.7@gmail.com>
  Date = 23/02/10
"""

# Imports externals

# Imports internals
from HtpcUtils.App import App
from HtpcUtils.SubDaemon import SubDaemon
from HtpcUtils.EventManager import EventManager


# Main entry point
if __name__ == '__main__':
  app = App('sub-daemon')
  app.add_option('--cron', dest='cron',
      help='cron run',
      action='store_true', default=False)
  app.add_option('--add', dest='add',
      help='add a new video file to the subtitle queue',
      action='store_true', default=False)
  app.add_option('--delete', dest='delete',
      help='delete a video file from the subtitle queue',
      action='store_true', default=False)
  app.add_option('--list', dest='list',
      help='list all the pending subtitles in the queue',
      action='store_true', default=False)
  (params, args) = app.parse_args()

  app.updateConfig(app.parseConfigFilename('/etc/htpc-utils.yml') or {})
  eventManagerConfig = app.getConfig().get('EventManager',
      {'filename': 'test.rss'})
  eventManager = EventManager(
      eventManagerConfig.get('filename', 'test.rss'),
      eventManagerConfig.get('link'))
  subDaemon = SubDaemon(eventManager)

  if params.list:
    for subtitle in subDaemon.pendingList():
      print subtitle
    app.exit(0)

  if params.add:
    if len(args) != 2:
      app.getLogger().error('Invalid number of parameters')
      app.exit(1)
    videoFile = args.pop(0)
    subLanguage = args.pop(0)

    subDaemon.add(videoFile, subLanguage)
    app.exit(0)

  if params.delete:
    if len(args) != 1:
      app.getLogger().error('Invalid number of parameters')
      app.exit(1)
    videoFile = args.pop(0)

    subDaemon.delete(videoFile)
    app.exit(0)

  if params.cron:
    subDaemon.cron()
    app.exit(0)

  app.getLogger().error('No operation provided')

